package com.zodiac.alioth.web.interceptor;

import com.zodiac.alioth.common.manager.AdminUserManager;
import com.zodiac.alioth.web.exception.AppException;
import com.zodiac.alioth.web.exception.AuthException;
import com.zodiac.alioth.web.security.LoginContextHelper;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * 鉴权
 *
 * @author zodiac
 */
@Aspect
@Order(0)
@Component
public class AuthAspect {

    private static final Logger logger = LoggerFactory.getLogger(AuthAspect.class);

//    @Resource
//    ResourceManager resourceManager;


    @Pointcut("@annotation(com.zodiac.alioth.common.annotation.AuthCheck)")
    public void authAdvice() {
    }

    /**
     * 判断是否有访问权限
     *
     * @param joinPoint
     */
    @Before("authAdvice()")
    public void before(JoinPoint joinPoint) {

        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        String url = request.getRequestURI();

        String loginUserId = LoginContextHelper.getLoginUserId();
        if (StringUtils.isEmpty(loginUserId)) {
            throw new AuthException("您尚未登录，请先登录");
        }
        //判断是否超级管理员
        if (AdminUserManager.isSuperAdmin(loginUserId)) {
            return;
        }

        //校验是否有权限
//        if (!resourceManager.canAccessUrl(url)) {
//            logger.error("用户={}, 无此权限, url={}", loginUserId, url);
//            throw new AuthException("你没有该操作权限，请联系管理员开通");
//        }

    }

}
